<template>
  <t-link
    v-permission="['system:order-contract-zheng:query']"
    theme="primary"
    @click="handleOpenDialog"
  >
    查看合同
  </t-link>
  <t-dialog v-model:visible="visible" attach="body" header="查看合同" width="58%">
    <!-- 内容 -->
    <template v-if="contractDetails.id">
      <div style="margin-bottom: var(--td-comp-margin-s)">
        <span v-if="contractDetails.result !== null" style="margin-left: var(--td-comp-margin-s)"
        ><t-tag :theme="getTagThemeAndLabel(contractDetails.result - 1).theme">{{
          getTagThemeAndLabel(contractDetails.result - 1).label
        }}</t-tag>
      </span>
      </div>      
      <t-descriptions  bordered :column="4">
        <t-descriptions-item  v-if="contractDetails.id"  :span="4">
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>合同编号</span>
          </template>
           {{ contractDetails.contractNo }}
        </t-descriptions-item>
        <t-descriptions-item :span="2">
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>施工模板</span>
          </template>
          {{ stageModelName }}
        </t-descriptions-item>
        <t-descriptions-item >
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>纯设计</span>
          </template>
          {{ dictionaryStore.analysis('is_type', contractDetails.isDesigner)  }}
        </t-descriptions-item>
        <t-descriptions-item >
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>是否有产品</span>
          </template>
          {{ dictionaryStore.analysis('is_type', contractDetails.isProduct)   }}
        </t-descriptions-item>
        <t-descriptions-item :span="2">
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>合同总价</span>
          </template>
          {{ contractDetails.contractPrice }}
        </t-descriptions-item>
        <t-descriptions-item :span="2">
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>签约时间</span>
          </template>
          {{ contractDetails.contractSigningTime?dayjs(contractDetails.contractSigningTime).format('YYYY-MM-DD HH:mm:ss'):'' }}
        </t-descriptions-item>
        <t-descriptions-item >
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>合同开工时间</span>
          </template>
          {{ contractDetails.contractBeginTime?dayjs(contractDetails.contractBeginTime).format('YYYY-MM-DD'):'' }}
        </t-descriptions-item>
        <t-descriptions-item >
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>合同完工时间</span>
          </template>
          {{ contractDetails.contractEndTime?dayjs(contractDetails.contractEndTime).format('YYYY-MM-DD'):'' }}
        </t-descriptions-item>
        <t-descriptions-item label="实际开工时间">
          {{ contractDetails.actualBeginTime?dayjs(contractDetails.actualBeginTime).format('YYYY-MM-DD'):'' }}
        </t-descriptions-item>
        <t-descriptions-item label="实际完工时间">
          {{ contractDetails.actualEndTime?dayjs(contractDetails.actualEndTime).format('YYYY-MM-DD'):'' }}
        </t-descriptions-item>
        <t-descriptions-item label="合同文件" :span="4">
          <upload v-model:files="contractDetails.contractFile" multiple disabled />
        </t-descriptions-item>
        <t-descriptions-item label="备注" :span="4">{{ contractDetails.remark }}</t-descriptions-item>
        <t-descriptions-item label="赠品" :span="4">
       
          <div style="width: 100%">
              <t-table
                row-key="id"
                :data="contractDetails.gift"
                :columns="[
                  { colKey: 'name',align: 'center', title: '赠品名称'},
                  { colKey: 'fileUrl',align: 'center', title: '赠品图片'},
                  { colKey: 'money',align: 'center', title: '赠品价值金额'},
                ]"
                bordered
                size="small"
                stripe
                hover
                >
                  
                  <template #fileUrl="{ row }">
                    <image-viewer  :images="[row.fileUrl]" width="50px" height="50px" />
                  </template>
              </t-table>
            </div>
        </t-descriptions-item>
        <t-descriptions-item :span="4">
          <template #label>
            <span><span style="color: #d54941;margin-right:4px;">*</span>分期付款</span>
          </template>
          <div style="width: 100%">
              <t-table
                row-key="id"
                :data="contractDetails.payList"
                :columns="[
                  { colKey: 'payNumber', align: 'center',title: '收款期数' },
                  { colKey: 'paymentStage',align: 'center', title: '收款阶段' },
                  { colKey: 'proportion',align: 'center', title: '收款比例(%)' },
                  { colKey: 'amountOfMoney',align: 'center', title: '期款金额(元)' },
                  { colKey: 'xjje', align: 'center',title: '洽商金额(元)' },
                  { colKey: 'reminderForCollectionStage', align: 'center',title: '收款提醒阶段',width:280 },
                ]"
                bordered
                size="small"
                stripe
                hover
                >
                <template #reminderForCollectionStage="{ row, rowIndex }">
                  <t-cascader
                  v-model:value="row.reminderForCollectionStage"
                  :options="stageTree"
                  :keys="{ value: 'id', label: 'stageName' }"
                  placeholder=""
                  filterable
                  clearable
                  :readonly="true"
                  class="text-only-cascader"

                />
                </template>
                  
                  <template #payStatus="{ row }">
                    {{ dictionaryStore.analysis('decoration_construction_order_stage', row.payStatus) }}
                  </template>
              </t-table>
            </div>
        </t-descriptions-item>
      </t-descriptions>


    </template>
    <!-- 空 -->
    <t-empty v-else style="margin: 100px" title="暂无合同信息">
      
    </t-empty>
    <template #footer>
      <t-button theme="default" @click="visible = false">取消</t-button>
      <!-- <t-button :loading="loadingSubmit" @click="handleSelectedIds">保存</t-button> -->
    </template>
  </t-dialog>
 
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { MessagePlugin } from 'tdesign-vue-next';
import { computed, ref } from 'vue';
import { getContractByOrderId, orderContractZhengCRUD } from '@/api/finance/contract';
import { engineeringConfigCRUD, engineeringModelCRUD } from '@/api/config/common-config';
import ImageViewer from '@/components/image-viewer/index.vue';
import Upload from '@/components/upload/index.vue';
import { useDictionaryStore } from '@/store';
import listToTree from '@/utils/listToTree';

interface TagThemeAndLabel {
  theme: 'warning' | 'success' | 'danger' | 'default';
  label: string;
}
// 字典仓库
const dictionaryStore = useDictionaryStore();

// props
const props = defineProps({
  // 期款id
  id: {
    type: Number,
    required: true,
  },
  orderId: {
    type: Number,
    required: true,
  },
  companyId: {
    type: Number,
    required: false,
  }
});
// emits
const emits = defineEmits(['requestSuccess']);

const visible = ref(false)
// 打开对话框
const handleOpenDialog = () => {
  visible.value = true
  handleGetSimpleStageTree();
  handleGetContractDetails();
  handleGetstageModelOptions();
}
// 整装合同id
const zzContractId = ref()
// 合同详情
const contractDetails = ref<Record<string, any>>({});
// 精简节点树
const stageTree = ref([]);
// 处理获取精简节点
const handleGetSimpleStageTree = () => {
  const params = {
    pageSize:-1
  }
  engineeringConfigCRUD.page(params).then((data) => {
    stageTree.value = listToTree(data.list);
  });
};
// 处理获取合同详情
const handleGetContractDetails = () => {
  const params = {
    orderId: props.orderId,
  };
  getContractByOrderId(params)
    .then((data) => {
      // if (data) contractDetails.value = data.list[0] || {};
      if(data.total>0) {
        zzContractId.value = data.list[0].id
        handleGetContractZheng({id:data.list[0].id})
      } else {
        contractDetails.value={}
      } 
    })
    .catch(({ message }) => {
      MessagePlugin.error(message);
    })
    
};
const handleGetContractZheng = (params:Record<string,any>) =>{
  orderContractZhengCRUD.get(params).then(res=>{
    contractDetails.value=res
  })
};
// 根据审批状态获取标签样式以及文字
const getTagThemeAndLabel = (result: number): TagThemeAndLabel => {
  const map: TagThemeAndLabel[] = [
    {
      theme: 'warning',
      label: '待审批',
    },
    {
      theme: 'success',
      label: '审批通过',
    },
    {
      theme: 'danger',
      label: '审批不通过',
    },
    {
      theme: 'danger',
      label: '审批已取消',
    },
  ];

  return result in map ? map[result] : { theme: 'default', label: '未知状态' };
};
// 施工模板模板列表
const stageModelOptions = ref([]);
// 处理获取施工模板模板列表
const handleGetstageModelOptions = () => {
  const params = {
    companyId: props.companyId,
    pageSize: -1,
  };
  engineeringModelCRUD.page(params).then((data) => {
    stageModelOptions.value = data.list;
  });
};

// 计算属性，用于查找匹配的stageModel名称
const stageModelName = computed(() => {
  if (!contractDetails.value.stageModelId || stageModelOptions.value.length === 0) {
    return '';
  }
  const found = stageModelOptions.value.find(
    item => item.id === contractDetails.value.stageModelId
  );
  return found ? found.name : contractDetails.value.stageModelId;
});
// 处理对话框请求成功
const handleDialogRequestSuccess = (result: Record<string, any>) => {
  emits('requestSuccess', result);
};
</script>
<style lang="less" scoped>
.text-only-cascader {
  :deep(.t-input__suffix-icon) {
    display: none;
  }
  
}
</style>
